import React, { useRef, useState, useEffect } from 'react';
import ATable, { ATableColumn, SearchToolBarProps } from '@apulis/table';
import type { ActionType } from '@apulis/table/lib/typing';
import { apwsfRequest,  } from '@/utils/request';
import { modelAPI, modelVersionAPI, getModelVersions } from '../service';
import { Table, Button, Modal, Popover } from 'antd'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import trans from '@/utils/translate';
import format from '@/utils/format';

export interface model {
  // name: string;
  engine: string;
  modelName: string;
  id: number;
  version: string;
  versionId: number;
  task: string;
  field: string;
  source: string;
  updatedAt: string;
  devices: Array<Object>;
};
interface modelVersion {
  name: string; // 模型版本
  modelName: string;
  modelId: string;
  versionId: number; // 版本 ID
  updatedAt: string;
};
interface Props {
  getModel: any;
  model?: model;
};

const SelectModel: React.FC<Props> = (props) => {
  const modelRef = useRef<ActionType>();
  const modelVersionRef = useRef<ActionType>();

  const [expandedKeysModel, setExpandedKeysModel] = useState<React.Key[]>(['']);
  const [modelKeys, setModelKeys] = useState<React.Key[]>([]);
  const [models, setModels] = useState<model[]>([])
  const [modalModel, setModalModel] = useState(false); // 控制节点选择弹窗


  const columnsModel: ATableColumn<model>[] = [
    {
      title: trans('deployOnline.centralInference.modelName'),
      dataIndex: 'name',
    },
    {
      title: trans('deployOnline.edgeInference.add.modelType'),
      dataIndex: 'type',
      render: (text, record) => (record.field && record.task) ? `${record.field}/${record.task}` : ''
    },
    {
      title: trans('deployOnline.edgeInference.add.versionCount'),
      dataIndex: 'versionCount',
    },
    {
      title: trans('deployOnline.centralInference.source'),
      dataIndex: 'source',
      render: (text) => text ? trans(`model.source.${text}`) : ''
    },
    {
      title: trans('deployOnline.edgeInference.add.createdAt'),
      dataIndex: 'createdAt',
      format: 'time',
      sorter: true,
    },
  ];
  const columnsModelVersion: ATableColumn<modelVersion>[] = [
    {
      title: trans('deployOnline.edgeInference.add.modelVersion'),
      dataIndex: 'name',
    },
    {
      title: trans('deployOnline.edgeInference.add.engine'),
      dataIndex: 'engine',
      render: (text: string) => (
        <Popover content={
          <div style={{width: '300px', wordBreak: 'break-all'}}>
            {text}
          </div>
        }>
          <span className='textEllipsis' style={{width: '200px', display: 'inline-block', marginBottom: '-6px'}}>
            {text}
          </span>
        </Popover>
      )
    },
    {
      title: trans('deployOnline.edgeInference.add.backbone'),
      dataIndex: 'backbone',
    },
    {
      title: trans('deployOnline.edgeInference.add.datasetName'),
      dataIndex: 'datasetName',
    },
    {
      title: trans('deployOnline.edgeInference.add.updateAt'),
      dataIndex: 'updatedAt',
      format: 'time'
    },
  ];
  const columnsModelSelect: ATableColumn<model>[] = [
    {
      title: trans('deployOnline.centralInference.modelName'),
      dataIndex: 'modelName',
    },
    {
      title: '模型类型',
      dataIndex: 'engine',
      key: 'engine',
      render: (text, row) => {
        return <span>{row.task}-{row.field}</span>
      }
    },
    {
      title: trans('deployOnline.edgeInference.add.modelVersion'),
      dataIndex: 'version',
    },
    {
      title: trans('deployOnline.centralInference.source'),
      dataIndex: 'source',
      render: (text: string) => text ? trans(`model.source.${text}`) : ''
    },
    {
      title: trans('deployOnline.edgeInference.add.updatedAt'),
      dataIndex: 'updatedAt',
      render: (text) => format(text),
    },
    {
      title: trans('nodeManagement.edgeNode.operation'),
      render: () => (
        <Button
          onClick={deleteModel}
          danger
          type='text'
        >{trans('common.delete')}</Button>
      )
    }
  ];
  const searchList: SearchToolBarProps[] = [
    {
      type: 'select',
      name: 'source',
      label: '来源',
      selectOptions: [
        { label: trans(`model.source.preset`), value: 'preset' },
        { label: trans(`model.source.publish`), value: 'publish' },
        { label: trans(`model.source.custom`), value: 'custom' },
      ],
      placeholder: '请选择来源',
      selectProps: { allowClear: true }
    },
    {
      type: 'input',
      name: 'name',
      label: '模型名称',
      placeholder: '请输入模型名称',
      inputProps: { allowClear: true },
    }
  ]

  const expandModelChange = (rows: Readonly<React.Key[]>) => {
    const arrTemp: React.Key[] = ['']
    setExpandedKeysModel([...arrTemp, rows[rows.length - 1]])
    setModelKeys([]);
  }
  const selectModel = () => {
    props.getModel(models);
    setModalModel(false);
  }
  const deleteModel = () => {
    setModels([]);
    props.getModel([]);
    setModels([]);
    setModelKeys([]);
    modelRef.current?.reload();
    modelVersionRef.current?.reload();
  }

  useEffect(() => {
    const { model } = props as { model: model };
    // 目前只支持选择一个模型，因此，获取第一个模型的信息
    if (model) {
      setModels([model]);
      setModelKeys([model.versionId]);
    }
  }, [props])

  return (
    <>
      {
        (models.length > 0 && !modalModel) &&
        <Table
          dataSource={models}
          columns={columnsModelSelect}
          rowKey='name'
          pagination={false}
        ></Table>
      }
      <Button
        icon={<PlusOutlined />}
        onClick={() => setModalModel(true)}
      >{trans('deployOnline.edgeInference.add.addModel')}</Button>
      <Modal
        width='1000px'
        visible={modalModel}
        onOk={selectModel}
        onCancel={() => setModalModel(false)}
        title='选择模型'>
        <ATable
          actionRef={modelRef}
          request={apwsfRequest}
          dataSourceAPIPath={modelAPI}
          columns={columnsModel}
          rowKey='id'
          reloadIcon={false}
          searchToolBar={searchList}
          expandable={{
            expandedRowKeys: expandedKeysModel,
            onExpandedRowsChange: (expandedRows) => {expandModelChange(expandedRows)},
            expandedRowRender: record => (
              <ATable
                rowSelection={{
                  type: 'radio',
                  onChange: (selectedRowKeys, selectedRows: modelVersion[]) => {
                    setModelKeys(selectedRowKeys);
                    const { modelName, name, versionId } = selectedRows[0]
                    setModels([{
                      id: record.id,
                      engine: record.engine,
                      modelName,
                      // name,
                      version: name,
                      versionId,
                      source: record.source,
                      updatedAt: record.updatedAt,
                      task: record.task,
                      field: record.field,
                      devices: record.devices,
                    }]);
                  },
                  selectedRowKeys: modelKeys
                }}
                actionRef={modelVersionRef}
                request={apwsfRequest}
                dataSourceAPIPath={`${modelVersionAPI}/${record.id}`}
                columns={columnsModelVersion}
                rowKey='versionId'
                reloadIcon={false}
              ></ATable>
            )
          }}
        ></ATable>
      </Modal>
    </>
  )
}

export default SelectModel;
